<script setup>
import { ref, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import { appWindow } from "@tauri-apps/api/window";
import { ElNotification } from 'element-plus'
// import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx';


let loaderflag = ref(false);
let file = ref(null);// 上传的文件
let excel_filder = ref([]);// excel字段名
let num = ref("");// 查询运输计划指令

const tableData = ref([]);

let screenHeight = ref(window.innerHeight - 100);


// 动态生成的列数组
const columns = ref([]);


// 获取 tableData 的第一行数据的键名和值
function generateColumns() {
  if (tableData.value.length > 0) {
    const firstRow = tableData.value[0];
    columns.value = Object.keys(firstRow).map(key => ({
      prop: key,
      label: key.charAt(0).toUpperCase() + key.slice(1)
    }));
  }
}


// 导出excel
const exportExcel = async (nums) => {

  if (nums == 1) {
    if (tableData.value.length == 0) {
      ElNotification({
        title: 'Error',
        message: '没有数据',
        type: 'error',
      });
      return;
    }
  } else if (nums == 2) {
    if (month_df_Data.value.length == 0) {
      ElNotification({
        title: 'Error',
        message: '没有月货量数据',
        type: 'error',
      });
      return;
    }
  }

  const ws = XLSX.utils.json_to_sheet(nums == 1 ? tableData.value : month_df_Data.value); // 将数据转换为工作表
  const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
  const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

  // 创建Blob对象并使用URL.createObjectURL方法生成URL
  const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
  const url = URL.createObjectURL(data);

  // 创建隐藏的可下载链接
  const link = document.createElement('a');
  link.href = url;
  link.style.display = 'none';
  link.download = 'data.xlsx'; // 设置下载文件名
  document.body.appendChild(link);

  // 触发点击下载
  link.click();
  // 清理
  setTimeout(() => {
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }, 100);
}

window.addEventListener('resize', function () {
  screenHeight.value = window.innerHeight - 100;
});



function readFile() {
  const fileReader = new FileReader() // 创建一个FileReader对象

  // 监听文件读取完成事件
  fileReader.onload = async (event) => {
    const binaryData = event.target.result
    const workbook = XLSX.read(binaryData, { type: 'binary' })

    // 提取第一个工作表的数据
    // const worksheet = workbook.Sheets[workbook.SheetNames[0]]
    const worksheet = workbook.Sheets[excel_filder.value[excel_filder.value.length-1]];
    const data = XLSX.utils.sheet_to_json(worksheet, { defval: '' });
    const filteredData = data.map(item => {
      return excel_filder.value.slice(0,-1).reduce((acc, key) => {
        if (item.hasOwnProperty(key)) {
          acc[key] = item[key];
        }
        return acc;
      }, {});
    });


    const json_data = JSON.stringify(filteredData);
    tableData.value = [];
    loaderflag.value = true;
    await invoke("greet", { num: num.value, jsonstring: json_data }).then(result => {
      if (result.startsWith("错误")) {
        alert(result);
        return;
      }
      if (num.value == "1") {
        tableData.value = JSON.parse(result);
        generateColumns();
      }
    }).catch(e => {
      alert(e);
    }).finally(() => {
    isAlwaysOnTop.value = false;
    loaderflag.value = false;
  });;
  }

  // 监听文件读取失败事件
  fileReader.onerror = () => {
    console.error('Failed to read the Excel file.')
  }

  // 读取文件内容
  //当文件读取完成后，FileReader对象的onload事件回调会被触发。在此回调中，可以访问event.target.result获取到读取完成的ArrayBuffer数据，然后使用XLSX库的read方法解析这个二进制数据为工作簿对象，进而进行数据提取和处理。
  //这一句是必不可少的，它启动了从用户选择的Excel文件到内存中二进制数据的读取过程，为后续的文件解析和数据处理奠定了基础。如果省略了这一步，文件内容将无法被读取，onload事件也不会触发，导致无法继续执行后续的Excel数据解析逻辑
  fileReader.readAsArrayBuffer(file.value.raw) // 读取文件内容，并将文件内容以ArrayBuffer的形式读入
}


async function handleFileChange_air(file1) {
  file.value = file1;
  num.value = "1";
  let filder_list = [];
  await invoke("greet", { num: "4", jsonstring: '无' }).then(result => {
      if (result.startsWith("错误")) {
        isAlwaysOnTop.value = false;
        alert(result);
        return;
      }
      filder_list = JSON.parse(result);
    }).catch(e => {
      isAlwaysOnTop.value = false;
      alert(e);
    });
  excel_filder.value = filder_list;
  readFile(); // 读取文件内容
}

async function handleFileChange_sea(file1) {
  file.value = file1;
  num.value = "2";
  let filder_list = [];
  await invoke("greet", { num: "5", jsonstring: '无' }).then(result => {
      if (result.startsWith("错误")) {
        isAlwaysOnTop.value = false;
        alert(result);
        return;
      }
      filder_list = JSON.parse(result);
    }).catch(e => {
      isAlwaysOnTop.value = false;
      alert(e);
    });
  excel_filder.value = filder_list;
  readFile(); // 读取文件内容
}

async function handleFileChange_si(file1) {
  file.value = file1;
  num.value = "3";
  let filder_list = [];
  await invoke("greet", { num: "6", jsonstring: '无' }).then(result => {
      if (result.startsWith("错误")) {
        isAlwaysOnTop.value = false;
        alert(result);
        return;
      }
      filder_list = JSON.parse(result);
    }).catch(e => {
      isAlwaysOnTop.value = false;
      alert(e);
    });
  excel_filder.value = filder_list;
  readFile(); // 读取文件内容
}


onMounted(() => {
  document.addEventListener('DOMContentLoaded', () => {
    // 阻止默认的文件拖放行为
    document.addEventListener('dragover', event => {
      event.preventDefault();
    });

    document.addEventListener('drop', event => {
      event.preventDefault();
      const files = event.dataTransfer.files;
      console.log('Files dropped:', files);
      // 在这里处理文件拖放事件
    });
  });

});

</script>

<template>
   <dev class="container">
    <!-- 加载动画 -->
   <div class="loader" v-if="loaderflag">
      <h5>正在创建邮件...</h5>
      <div class="box-1"> </div>
    </div>
    <!-- 头部 -->
    <div class="header">

        <el-upload class="upload-demo" drag accept=".xlsx, .xls" :on-change="handleFileChange_air" :auto-upload="false" :show-file-list="false" style="color: #626AEF;">
          <em>空运(查询运输计划指令)</em>
      </el-upload>

      <el-upload class="upload-demo" drag accept=".xlsx, .xls" :on-change="handleFileChange_sea" :auto-upload="false" :show-file-list="false" style="color: #b68f66;">
        <em>海运(查询运输计划指令)</em>
      </el-upload>

      <el-upload class="upload-demo" drag accept=".xlsx, .xls" :on-change="handleFileChange_si" :auto-upload="false" :show-file-list="false" style="color: red;">
        <em>SI制作(查看全部指令)</em>
      </el-upload>

     

<!-- 
      <el-dialog v-model="popconfirmVisible" title="系统提示" modal="false">
        <template #header>
          <el-text class="mx-1" type="danger">请选择运输计划指令类型</el-text>
        </template>

        <template #footer>
          <el-button type="primary" @click="selectTransport('air')">air</el-button>
          <el-button type="success" @click="selectTransport('sea')">sea</el-button>
          <el-button type="warning" @click="selectTransport('si')">si</el-button>
        </template>
      </el-dialog> -->


    </div>

    <!-- 内容 -->
    <div class="content">

      <el-scrollbar :height="screenHeight" style="color: red;">
        <el-table :data="tableData" :height="screenHeight" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="80" />
          <!-- 动态生成的列 -->
          <template v-for="(column, index) in columns" :key="index">
            <el-table-column :prop="column.prop" :label="column.label" />
          </template>
        </el-table>
      </el-scrollbar>

    </div>

      

   </dev>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  /* 使用视口高度来使容器填满整个屏幕 */
  overflow: hidden;
  /* 防止内容滚动 */
}

.loader {
  display: flex;
  /* 使 .loader 成为 Flex 容器 */
  flex-direction: column;
  /* 设置主轴方向为垂直 */
  align-items: center;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* 使用负边距来居中元素 */
  z-index: 100;

  /* 其他样式... */
  h5 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #626AEF;
    z-index: 200;
  }

}

.overlay {
  pointer-events: none;
  /* 禁用鼠标事件 */
  z-index: 1;
  /* 确保这个层在 loader 之下 */
  /* 其他样式... */
}

.box-1 {
  position: relative;
  height: 450px;
  width: 450px;
  background-color: #FFFFFF;
  background-image: linear-gradient(135deg, #FFFFFF 0%, #6284FF 34%, #FF0000 100%);
  border-radius: 50%;
  animation: rotate 3s linear infinite;
  box-shadow: rgba(17, 17, 26, 0.1) 0px 1px 0px, rgba(17, 17, 26, 0.1) 0px 8px 24px, rgba(17, 17, 26, 0.1) 0px 16px 48px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.box-1::before {
  content: '';
  position: absolute;
  inset: 15px;
  background: #f5f5f5;
  border-radius: 50%;
  box-shadow: rgb(204, 219, 232) 3px 3px 6px 0px inset, rgba(255, 255, 255, 0.5) -3px -3px 6px 1px inset;
}

.loader span {
  text-align: center;
  position: absolute;
  top: 65px;
  left: 25px;
  color: black;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  letter-spacing: 2px;
  font-weight: 800;
  font-size: 1rem;
  animation: text-animate412 3s linear infinite;
}

@keyframes text-animate412 {

  10% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}




.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}

.content {
  flex: 3;

}
::v-deep .el-upload-dragger{
  
  margin: 0;
  padding: 0;
  width: 300px;
  height:80px;

  // 字体居中
  line-height: 80px;
  justify-content: center;
  align-items: center;
  border: #626AEF 1px dashed;
}
.upload-demo {
  position: relative;
  margin: 0 10px;
}
em {
  // 绝对定位到父元素的中间
  position: absolute;
  top: -10%;
  left: 10%;
  // 字体大小
  font-size: 20px;
  // 字体颜色
  
  // 字体粗细
  font-weight: bold;
  // 字体样式
  font-style: normal;
  // 字体变小
  transform: scale(0.8);
}
</style>
